package com.k8.rpc.url;

import com.k8.common.util.StrUtil;

public class RegistrySignature {
    String regex = "^((([0-9]{1,3}\\\\.){3}[0-9]{1,3})|(\\[([0-9a-fA-F:]+)\\])):([0-9]{1,5})$";
    private final String protocol;
    private final String addr;

    public RegistrySignature(String protocol, String addr) {
        if (StrUtil.isEmpty(protocol)) throw new IllegalArgumentException("Protocol is empty");
        this.protocol = protocol;
        if (StrUtil.isEmpty(addr)) throw new IllegalArgumentException("Addr is empty");
        if (addr.matches(regex)) throw new IllegalArgumentException("Addr is error");
        this.addr = addr;
    }

    public RegistrySignature(URL url) {
        this.protocol = url.getProtocol();
        this.addr = url.getAddress().getAddr();
        if (StrUtil.isEmpty(this.protocol)) throw new IllegalArgumentException("Protocol is empty");
        if (StrUtil.isEmpty(this.addr)) throw new IllegalArgumentException("Addr is empty");
        if (this.addr.matches(regex)) throw new IllegalArgumentException("Addr is error");
    }

    public String getSignature() {
        return (protocol + ":" + this.addr).replaceAll("/", ":");
    }

    public String getProtocol() {
        return protocol;
    }

    public String getAddr() {
        return addr;
    }
}
